<template>
<ul class="link">
	<li v-repeat="its : list"><a v-attr="href:formatLink(its.link)" target="_blank" v-text="its.name"></a></li>
	<li>
		<a href="javascript:;" class="edit" v-on="click:isOpen=true">网址编辑</a>
	</li>
</ul>
<div id="custom-box" v-show="isOpen">
    <div id="add-link">
        <h3>网址编辑<span class="close" v-on="click:isOpen=false"></span></h3>
        <div class="all">
            <ul>
                <li v-repeat="item : list"><a>{{item.name}}<span class="delete" v-on="click : deleteLink(item.id)"></span></a></li>
            </ul>
            <div class="add">
                <p>
                    <label for="">名称：</label>
                    <input type="text" v-model="data.name" maxlength="5">
                </p>
                <p>
                    <label for="">链接：</label>
                    <input type="text" v-model="data.link" placeholder="http://">
                </p>
                <a href="javascript:;" v-on="click : addLink()">添加</a>
            </div>
        </div>
    </div>
    <div id="dimmer" class="f-fix f-hide" v-on="click : toggle()"></div>
</div>
</template>

<script>
var _ = require('../../static/util'),
	link = require('../../static/json/custom.json');

module.exports = {
	data : function(){
		return {
			list : [],
			isOpen : false,
			NAME_LIST : 'cs_add_list',
			data : {
				name : '',
				link : ''
			}
		}
	},
	compiled : function(){
		this.init();
	},
	methods : {
		formatLink : function(link){
			return /http:\/\//ig.test(link) ? link : 'http://'+link;
		},
		/**
		 * [copyLink description]
		 * @param  {[type]} data [description]
		 * @return {[type]}      [description]
		 */
		copyLink : function(data){
			var that = this;

			data.forEach(function(x, i){
				that.list.$set(i, x);
			});
		},
		/**
		 * [获取本地存储的链接列表]
		 * @return {[type]} [description]
		 */
		getStorageList : function(){
			return _.getItem(this.NAME_LIST);
		},
		/**
		 * [如果是第一次访问，将初始列表存储至本地]
		 * @return {[type]} [description]
		 */
		saveLink : function(data){
			_.setItem(this.NAME_LIST, data);
			_.setItem(this.NAME_STATUS, 'over');
		},

		clearInput : function(){
			this.data.link = "";
			this.data.name = "";
		},

		checkData : function(data){
			var status = 1;

			for (var i in data) {
				if (data[i] === "") {
					status = 0;
				}
			}

			return status;
		},

		addLink : function(){
			var that = this,
				status = that.checkData(that.data);

			if (status === 1) {

				that.list.push({
					link : that.data.link,
					name : that.data.name,
					id : +new Date() + ""
				});
				that.saveLink(that.list);
				that.clearInput();
			} else {
				alert("请填写完整！")
			}
		},

		deleteLink : function(id){
			var that = this;

			that.list.forEach(function(x, i){
				if (x.id === id) {
					that.list.$remove(i);
				}
			});

			that.saveLink(that.list);
		},

		init : function(){
			var list = this.getStorageList();

			list ? this.copyLink(list) : this.saveLink(link);

		}
	}
}
</script>